import request from "./request";

// 定义音频响应数据的接口
interface AudioResponse {
  audioData: {
    data: string;
    addition?: {
      duration?: string;
    };
    operation?: string;
    reqid?: string;
    sequence?: number;
  };
}

class AudioManager {
  // 静态属性存储唯一实例
  private static instance: AudioManager;
  
  // 私有属性
  private audio: HTMLAudioElement;
  private currentContent?: string;
  private isPlaying: boolean = false;
  
  // 私有构造函数，防止外部直接实例化
  private constructor() {
    this.audio = new Audio();
    // 监听播放结束事件
    this.audio.addEventListener('ended', () => {
      this.isPlaying = false;
    });
  }
  
  // 获取单例实例
  public static getInstance(): AudioManager {
    if (!AudioManager.instance) {
      AudioManager.instance = new AudioManager();
    }
    return AudioManager.instance;
  }
  
  // 播放音频
  public async play(content: string): Promise<boolean> {
    try {
      // 如果内容相同且正在播放，则暂停
      if (this.currentContent === content && this.isPlaying) {
        return this.pause();
      }
      
      // 如果内容不同，重新请求音频
      if (this.currentContent !== content) {
        // 先暂停当前播放
        if (this.isPlaying) {
          this.pause();
        }
        
        // 请求新的音频数据
        const response = await request.post<AudioResponse>('/api/deepSeek/dialogAudio', {
          contentText: content,
          voiceType: "qiniu_zh_male_ybxknjs"
        });
        
        // 验证响应数据
        if (!response?.audioData?.data) {
          throw new Error('未获取到有效的音频数据');
        }
        
        // 转换为DataURL并设置音频源
        const audioDataUrl = this.base64ToDataUrl(response.audioData.data, 'audio/mpeg');
        this.audio.src = audioDataUrl;
        this.currentContent = content;
      }
      
      // 播放音频
      await this.audio.play();
      this.isPlaying = true;
      console.log('音频开始播放');
      return true;
    } catch (error) {
      console.error('音频播放失败:', error);
      this.isPlaying = false;
      return false;
    }
  }
  
  // 暂停音频
  public pause(): boolean {
    if (this.isPlaying) {
      this.audio.pause();
      this.isPlaying = false;
      console.log('音频已暂停');
    }
    return this.isPlaying;
  }
  
  // 停止播放并重置
  public stop(): void {
    this.pause();
    this.audio.currentTime = 0; // 重置到开始位置
    this.currentContent = undefined;
    console.log('音频已停止');
  }
  
  // 获取当前播放状态
  public getIsPlaying(): boolean {
    return this.isPlaying;
  }
  
  // 获取当前播放内容
  public getCurrentContent(): string | undefined {
    return this.currentContent;
  }
  
  // Base64转DataURL的私有方法
  private base64ToDataUrl(base64String: string, mimeType: string): string {
    if (typeof base64String !== 'string' || typeof mimeType !== 'string') {
      throw new Error('输入必须是字符串类型');
    }
    return `data:${mimeType};base64,${base64String}`;
  }
}

// 初始化全局音频管理器实例
const audioManager = AudioManager.getInstance();

export default audioManager;
